#!/usr/bin/bash
pro_base="$(cd `dirname $(readlink -f $0)`;pwd)"        # program base directory. readlink是为了获取脚本的真实路径
pro_root="${pro_base##*/}"                              # 我的程序的根目录名字.   readlink使得ln创建的软链也能正确地执行
pro_name="$(readlink -f $0 | sed 's#^.*/##; s#.sh$##')" # 删除'/'前的路径,删除'.sh'

source ${pro_base}/shared/include.sh || exit 1
Include ${pro_base}/${pro_name}/${pro_name}.conf ${pro_base}/${pro_name}/{usage,core}.sh
Include ${pro_base}/shared/prompt.sh

Help "$@"
[[ $# -lt 1 ]] && Usage && exit 1

[[ -d "${log_dir}" ]] || Eval_exit "mkdir -p '${log_dir}'"
set -o pipefail
host_list="${pro_base}/${pro_name}/${pro_name}.host"
rsync_verbose_log="${log_dir}/rsync_verbose.${today}.log"
exclude_file="${pro_base}/${pro_name}/${pro_name}.exclude"
verbose_temp="${log_dir}/${pro_name}.temp"

! [[ -f "${host_list}" ]] && PError "文件缺失: ['主机清单'文件] ${host_list}" && exit 1
! [[ -f "${exclude_file}" ]] && PError "文件缺失: ['排除pattern'文件] ${exclude_file}" && exit 1

# check format of configuration file
for i in `egrep -av $'^[ \t]{0,}#|^[ \t]{0,}$' ${host_list}`  # 将注释行和空白行去掉
do
    if [[ `echo $i |awk -F, '{print NF}'` != 2 ]]; then
        PError "格式不规范: ['主机清单'内容有误] 请修改'${host_list}',下面的内容不规范\n\t${i}"
        exit 1
    fi
done

if [[ $1 == '-i' ]];then
    fnInstallDependence
    exit
fi

{
fnCheckArgs "$@"

[[ -f "${verbose_temp}" ]] && rm -f "${verbose_temp}"
fnRsyncToRemote "$@" |& tee -a "${rsync_verbose_log}" "${verbose_temp}"
# 提示详细的log位置
PInfo "以下文件保存了今天的传输任务的详细信息:
    ${rsync_verbose_log}"
cat <<EOF
/*
 * * * * * * END * * * * * *
 */
EOF
} |& tee -a "${stdout_log}"

(( $? != 0 )) && exit 1             # subshell异常退出后,就不要再往下执行了,记得先set -o pipefail

read -p "$(PNote "需要查看本次传输任务的详细信息吗? (y/n): ")" answer
if [[ ${answer} == y || ${answer} == Y ]]; then
    awk '{
        if(/deleting/)
            {gsub(/deleting/,"\033[1;35m&\033[0m"); print}
        else {print $0}
    }' "${verbose_temp}" | less -iRM
fi
[[ -f "${verbose_temp}" ]] && rm -f "${verbose_temp}"